#!/bin/sh

echoerr() {
	echo "$@" >&2
}

setup() {
	cd "setup"
	for item in ./*.sh; do
		[ -x "$item" ] || continue;

		basename=$(basename "$item")
		"$item"
		if [ "$?" -ne "0" ]; then
			echoerr "Could not set up: $item";
			cd ".."
			return 1;
		fi;
	done;
	cd ".."

	return 0;
}

teardown() {
	cd "teardown"
	for item in ./*.sh; do
		[ -x "$item" ] || continue;

		basename=$(basename "$item")
		"$item"
		if [ "$?" -ne "0" ]; then
			echoerr "Could not tear down: $item";
			cd ".."
			return 1;
		fi;
	done;
	cd ".."

	return 0;
}

benchmark() {
	benchdir="$1"
	shift

	cd "$benchdir"
	for item in ./*.sh; do
		[ -x "$item" ] || continue;
		echo -n "$item "
		/bin/sh -c "TIMEFORMAT='%R %U %S %P'; time \"$item\" > /dev/null";
	done;
	cd ".."
}

command="$1"
case "$command" in
	setup)
		echo "Setting up..."
		setup;
		;;

	teardown)
		echo "Tearing down..."
		teardown;
		;;
	
	print)
		echo "Benchmarks:"
		for benchdir in ./benchmark[0-9]*; do
			echo "# Benchmark: $benchdir"
			[ -r "$benchdir/README" ] && cat "$benchdir/README";
			echo;
		done;
		;;

	"")
		setup;
		if [ "$?" -ne "0" ]; then
			echoerr "Setup failed, bailing out."
			exit 1;
		fi;
		echo "# All benchmarks."
		echo "# Time format: '%R %U %S %P'."
		for benchdir in ./benchmark[0-9]*; do
			echo "# Benchmark: $benchdir"
			[ -r "$benchdir/README" ] && sed 's/^/# /' "$benchdir/README";
			benchmark "$benchdir"

			# Force a sync.
			sync
		done;
		teardown;
		;;
	
	*)
		echoerr "Usage: $0 [|setup|teardown|print]"
		echoerr ""
		echoerr "Example: $0       - run all tests"
		echoerr "         $0 print - print test information"
		;;
esac
